package com.test.ssm.controller;

import com.test.ssm.pojo.HotelOrder;
import com.test.ssm.service.OrderService;
import com.test.ssm.wechat.PayUtil;
import com.test.ssm.wechat.WXPayUtil;
import com.test.ssm.wechat.ZxingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 徒有琴
 */
@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;

    @RequestMapping("orders.html")
    public String orders(Model model){
        List<HotelOrder> orders=orderService.getOrderList();
        model.addAttribute("orders",orders);
        return "orders";
    }
    @RequestMapping("wx_order_detail.html")
    public String orderDeteil(Integer id,Model model){
        HotelOrder order=orderService.getOrderById(id);
        model.addAttribute("order",order);
        return "wxpay";
    }

    @RequestMapping("worder_code.html")
    public void wxorder(Integer id, HttpServletRequest request, HttpServletResponse response) {
        HotelOrder order=orderService.getOrderById(id);
        Map<String, String> params = new HashMap<>();
        params.put("appid", PayUtil.APP_ID);
        params.put("mch_id", PayUtil.MCH_ID);
        params.put("nonce_str", System.currentTimeMillis() + "");
        params.put("body", "卢本伟的挂");
        params.put("out_trade_no", order.getOrderNum());
        params.put("total_fee", order.getPrice().toString());
        params.put("spbill_create_ip", request.getRemoteAddr());
        params.put("notify_url", "http://2361k301i0.iok.la:10923/wcallback.html");
        params.put("trade_type", "NATIVE");
        try {
            String xml = WXPayUtil.generateSignedXml(params, PayUtil.API_KEY);
            // System.out.println(xml);
            String res = PayUtil.doPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
            System.out.println(res);
            Map<String, String> result = WXPayUtil.xmlToMap(res);
            System.out.println(result.get("code_url"));
            BufferedImage img = ZxingUtil.createImage(result.get("code_url"), 300, 300);
            ImageIO.write(img, "JPEG", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
